#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      qs = require('querystring');

let html = `
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <form method = 'post'action = 'http://192.168.38.144:3000/'>
      <label>username:</label>
      <input type = 'text' name = 'userName'>
      </br>
      <label>password:</label>
      <input type = 'password' name = 'passWord'>
      </br>
      <label>&nbsp;</label>
      <input type = 'submit' value = 'login'>
    </form>
    <div>%</div>
  </body>
  </html>
`
http.createServer((req, res) => {
  //log(`${req.method} ${req.url} HTTP/${req.httpVersion}`)

  //log(req.headers)

  //log()
  
  if (req.url === '/') {
    if (req.method === 'GET') {
      // return html
      let html = fs.readFileSync('./04-form-server.html').toString('utf8')
      res.end(html)

    } else if (req.method === 'POST') {

        let data = ''
        req.on('data', (chunk) => {
          data += chunk
        })
        req.on('end', () => {
          let out = data
          console.log(data)
          html = html.replace('%', out)
          res.end(html)
        })
    } else {
        err(req, res)
    } 
  } else {
      err(req, res)
  }
}).listen(3000)

function err(req, res){
  res.statusCode = 404
  res.end(`${req.url} Not Found`)
}




